package com.zhkj.txg.module.order.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import com.zhkj.lib.base.BalanceChangeEvent
import com.zhkj.lib.base.CartChangeEvent
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.mine.popup.OrderCouponPopupWindow
import com.zhkj.txg.module.order.adapter.OrderGoodsAdapter
import com.zhkj.txg.module.order.entity.OrderAddressEntity
import com.zhkj.txg.module.order.entity.OrderPayEntity
import com.zhkj.txg.module.order.entity.OrderSubmitDetailEntity
import com.zhkj.txg.module.order.entity.OrderSubmitEntity
import com.zhkj.txg.module.order.popup.PayTypePopupWindow
import com.zhkj.txg.module.order.vm.OrderViewModel
import com.zhkj.txg.utils.PayUtils
import com.zhkj.txg.utils.WXPayEntity
import kotlinx.android.synthetic.main.activity_order_detail.*
import kotlinx.android.synthetic.main.item_order_address.*
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.*

class OrderSubmitActivity : ViewModelActivity<OrderViewModel>() {

    companion object {
        private val TYPE = "type"

        private val GOODS_ID = "goodsId"
        private val GOODS_NUM = "goodsNum"
        private val SHOP_ID = "shopId"

        private val CART_IDS = "cartIds"


        fun buyNow(context: Context, goodsId: Int, goodsNum: Int, shopId: Int) {
            val intent = Intent(context, OrderSubmitActivity::class.java).putExtra(TYPE, 0)
                .putExtra(GOODS_ID, goodsId).putExtra(GOODS_NUM, goodsNum).putExtra(SHOP_ID, shopId)
            context.startActivity(intent)
        }

        fun cartBuy(context: Context, cartIds: String) {
            Log.e("TAG", cartIds)
            val intent = Intent(context, OrderSubmitActivity::class.java).putExtra(TYPE, 1)
                .putExtra(CART_IDS, cartIds)
            context.startActivity(intent)
        }
    }

    override val layoutResId: Int = R.layout.activity_order_detail
    override fun setViewModel(): OrderViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleOrder

    private val REQUEST_ADDRESS = 100

    //    private val orderAdapter = OrderCartAdapter { uiPosition, content -> // 填写备注
//        viewModel.orderLiveData.value?.response?.data?.let {
//            it.cartList[uiPosition].orderDesc = content
//        }
//    }.apply {
//        setOnItemChildClickListener { _, view, position ->
//            when (view.id) {
//                R.id.viewSelectShopCoupon -> { // 选择优惠券
//                    val couponList = data[position].couponList
//                    if (couponList.isEmpty()) toast(getString(R.string.shop_coupon_empty))
//                    else with(orderCouponPopupWindow) {// 弹出优惠券PopupWindow
//                        type = OrderCouponPopupWindow.TYPE_SHOP
//                        uiPosition = position
//                        setData(couponList)
//                        showPopupWindow()
//                    }
//                }
//            }
//        }
//    }
    private val orderAdapter = OrderGoodsAdapter()
    private val payTypePopupWindow: PayTypePopupWindow by lazy {
        PayTypePopupWindow(this, { type, orderInfo ->
            val map = hashMapOf("order_sn" to orderInfo.orderSignNumber, "pay_type" to type)
            viewModel.payOrder(map)
        }, {
            if (intent.getIntExtra(TYPE, 0) == 1) {
                RxBus.post(CartChangeEvent())
            }
            OrderListActivity.open(this, 1)
            finish()
            true
        })
    }

    private var couponId = 0

    private val orderCouponPopupWindow: OrderCouponPopupWindow by lazy {
        OrderCouponPopupWindow(this) { type, uiPosition, coupon ->
            // 选中优惠券
            viewModel.orderLiveData.value?.response?.data?.let {
//                couponId = it.couponList[uiPosition].couponId
                couponId = coupon.id
                if (type == OrderCouponPopupWindow.TYPE_SHOP) { // 是店铺优惠券
                    // 设置优惠券
                    it.cartList[uiPosition].selectCoupon = coupon
                } else { // 是平台优惠券
                    it.selectCoupon = coupon
                }
                // 计算金额
                var totalCouponFee = BigDecimal(0)
                it.cartList.forEach { cart ->
                    if (cart.selectCoupon != null) {
                        totalCouponFee = totalCouponFee.add(BigDecimal(cart.selectCoupon!!.money))
                        cart.useCouponTotalPrice = BigDecimal(cart.shopTotalFee)
                            .subtract(BigDecimal(cart.selectCoupon!!.money)).toDouble()
                    }
                }
                if (it.selectCoupon != null) totalCouponFee =
                    totalCouponFee.add(BigDecimal(it.selectCoupon!!.money))
                it.useCouponTotalPrice =
                    BigDecimal(it.goodsTotalFee).subtract(totalCouponFee).toDouble()
                fillData(it, false)
            }
        }
    }

    override fun initViewModel() {
        // 订单详情数据观察者
        viewModel.orderLiveData.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                it.response?.data?.let { data ->
                    if (data.couponList.size == 0) {
                        fillData(data, true)
                    } else {
                        val order = data
                        order.useCouponTotalPrice =
                            order.useCouponTotalPrice - order.couponList[0].money
                        couponId = order.couponList[0].id
                        fillData(order, true, order.couponList[0].money)
                    }
                }
            }
        })
        // 微信支付结果观察者
        viewModel.payResult().observe(this, Observer {
            if (it.paySuccess) {
                // 通知购物车，需要刷新
                if (intent.getIntExtra(TYPE, 0) == 1) RxBus.post(CartChangeEvent())
                paySuccess()
            } else toast(it.payDesc)
        })
        // 订单支付信息数据观察者
        viewModel.payOrderLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let { order ->
                if (!order.isNeedPay) {
                    // 刷新个人中心余额
                    RxBus.post(BalanceChangeEvent())
                    // 通知购物车，需要刷新
                    if (intent.getIntExtra(TYPE, 0) == 1) RxBus.post(CartChangeEvent())
                    paySuccess()
                } else when (order.payType) {
                    OrderPayEntity.TYPE_WECHAT -> { // 微信支付
                        order.payInfo.let {
                            PayUtils.wxPay(this, Gson().fromJson(it, WXPayEntity::class.java))
                        }
                    }
                    // 支付宝支付
                    OrderPayEntity.TYPE_ALIPAY -> PayUtils.aliPay(this, order.payInfo, {
                        // 通知购物车，需要刷新
                        if (intent.getIntExtra(TYPE, 0) == 1) RxBus.post(CartChangeEvent())
                        paySuccess()
                    }, { toast(it) })
                    else -> Unit
                }
            }
        })
    }

    override fun initUI() {
        rvOrder.apply {
            layoutManager = LinearLayoutManager(this@OrderSubmitActivity)
            adapter = orderAdapter
        }
        btnAddress.setOnClickListener {
            AddressManagerActivity.selectAddress(this@OrderSubmitActivity, REQUEST_ADDRESS)
        }
        btnSubmit.setOnClickListener {
            if (distributionMode == 1) {
                if (viewModel.orderLiveData.value?.response?.data?.address == null) {
                    toast(getString(R.string.select_default_address))
                    return@setOnClickListener
                }
            }
            viewModel.orderLiveData.value?.response?.data?.let {
                val cartListString = viewModel.formatOrderRequestParam(it.cartList)

                val map = hashMapOf("shop_id" to CustomApplication.getShopId().toString())
                map["address_id"] = if (distributionMode == 0) "0" else it.address?.id.toString()
                map["cart_list"] = cartListString
                map["deal_type"] = distributionMode.toString()//配送方式id
                map["coupon_id"] = couponId.toString()//优惠券id
                viewModel.submitOrder(map).takeIf {
                    !it.hasObservers()
                }?.observe(this, Observer { response ->
                    handlerResponseStatus(response.status, response.statusTip)
                    if (response.status == HttpResponseStatus.Status.SUCCESS) {
                        response.response?.data?.let {
                            showPayPopup(it)
                        }
                    }
                })
            }
        }
        frame_coupon.setOnClickListener {
            viewModel.orderLiveData.value?.response?.data?.let {
                if (it.couponList.isEmpty()) toast(getString(R.string.platform_coupon_empty))
                else with(orderCouponPopupWindow) {// 弹出优惠券PopupWindow
                    type = OrderCouponPopupWindow.TYPE_PLATFORM
                    uiPosition = -1
                    setData(it.couponList)
                    showPopupWindow()
                }
            }
        }
        clDistribution.setOnClickListener {
            if (isDelivery == 1) {
                option.setPicker(distributions)
                option.show()
            }
        }
    }


    private val distributions = mutableListOf("自提", "送货")

    private var distributionMode: Int = 0

    private val option: OptionsPickerView<String> by lazy {
        OptionsPickerBuilder(this,
            OnOptionsSelectListener { options1, options2, options3, _ ->
                tvDistributionMode.text = distributions[options1]
                if (distributions[options1] == "送货") {
                    distributionMode = 1
                    btnAddress.visibility = View.VISIBLE
                    val order = orderSubmitDetailEntity
                        ?: return@OnOptionsSelectListener
                    order.useCouponTotalPrice =
                        order.useCouponTotalPrice + order.deliveryMoney.toDouble()
                    fillData(order, false)
                } else {
                    distributionMode = 0
                    btnAddress.visibility = View.GONE
                    val order = orderSubmitDetailEntity
                        ?: return@OnOptionsSelectListener
                    order.useCouponTotalPrice =
                        order.useCouponTotalPrice - order.deliveryMoney.toDouble()
                    fillData(order, false)
                }
            })
            .setCancelText("取消")
            .setSubmitText("确定")
            .build<String>()
    }

    override fun initData() {
        when (intent.getIntExtra(TYPE, 0)) {
            0 -> {
                val goodsId = intent.getIntExtra(GOODS_ID, 0)
                val goodsNum = intent.getIntExtra(GOODS_NUM, 0)
                val shopId = intent.getIntExtra(SHOP_ID, 0)
                viewModel.buyNow(AccountManager.getToken(), goodsId, goodsNum, shopId)
            }
            1 -> {
                intent.getStringExtra(CART_IDS)?.let {
                    viewModel.cartBuy(it.split(",") as MutableList<String>)
                }

            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_ADDRESS) {
            val address = data?.getSerializableExtra("data") as OrderAddressEntity
            viewModel.orderLiveData.value?.response?.data?.address = address
            fillAddress(address)
//            val goodsId = intent.getIntExtra(GOODS_ID, 0)
//            val goodsNum = intent.getIntExtra(GOODS_NUM, 0)
//            val shopId = intent.getIntExtra(SHOP_ID, 0)
//            when (intent.getIntExtra(TYPE, 0)) {
//                0 -> {
//                    viewModel.buyNow(
//                        AccountManager.getToken(), goodsId, goodsNum, shopId
//                    )
//                }
//                1 -> {
//                    intent.getStringExtra(CART_IDS)?.let {
//                        viewModel.cartBuy(it.split(",") as MutableList<String>, address.id)
//                    }
//                }
//            }
        }
    }

    var isDelivery = 1
    private var orderSubmitDetailEntity: OrderSubmitDetailEntity? = null

    //0自提，，1送货
    private fun fillData(order: OrderSubmitDetailEntity, isInit: Boolean, money: Double = 0.0) {

        this.orderSubmitDetailEntity = order
        fillAddress(order.address)
        tvCouponName.text = order.selectCoupon?.name ?: ""
        if (money == 0.0)
            tvShopCouponName.text = "-￥${order.selectCoupon?.money?.toString() ?: "0"}"
        else {
            tvShopCouponName.text = "-￥${money.toString()}"
        }
        tvTotalCount.text = "共${order.goodsTotalNum}件，合计"
        tvTotalAmount.text =
            SpanUtil.setMoneySymbol(String.format("%.2f", order.useCouponTotalPrice))
        tvFullDiscount.text =
            SpanUtil.setMoneySymbol(String.format("%.2f", order.discount.toDouble()))
        if (distributionMode == 0) {
            tvDeliveryMoney.text = SpanUtil.setMoneySymbol(String.format("%.2f", "0".toDouble()))
        } else {
            tvDeliveryMoney.text =
                SpanUtil.setMoneySymbol(String.format("%.2f", order.deliveryMoney.toDouble()))
        }

        val data = Date()
        val newTimeStart = Date(data.time + 1000 * 60 * 15)
        val newTimeEnd = Date(data.time + 1000 * 60 * 30)
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CANADA)
        val timeStart: String = simpleDateFormat.format(newTimeStart)
        val timeEnd: String = simpleDateFormat.format(newTimeEnd)
        val data1 = timeStart.substring(timeStart.indexOf("-") + 1, timeStart.indexOf(" "))
        val day = if (TimeUtils.isToday(timeStart)) "今天" else "明天"
        val time1 = timeStart.substring(timeStart.indexOf(" ") + 1, timeStart.lastIndexOf(":"))
        val time2 = timeEnd.substring(timeEnd.indexOf(" ") + 1, timeEnd.lastIndexOf(":"))

        tvSelfTimeContent.text = "$data1   $day  $time1 - $time2"

        order.cartList.forEach { it ->
            isDelivery = it.isDelivery
            tvDistributionMode.text = distributions[distributionMode]
            if (isInit) orderAdapter.setNewData(it.goodsList)
            else orderAdapter.notifyDataSetChanged()
        }
    }

    private fun fillAddress(address: OrderAddressEntity?) {
        if (address != null) {
            tvOrderAddressName.visibility = View.VISIBLE
            tvOrderAddressName.text = address.consignee
            tvOrderAddressMobile.visibility = View.VISIBLE
            tvOrderAddressMobile.text = address.mobile
            tvOrderAddress.text = address.address
        } else {
            tvOrderAddressName.visibility = View.GONE
            tvOrderAddressMobile.visibility = View.GONE
            tvOrderAddress.text = getString(R.string.select_address)
        }
    }

    private fun paySuccess() {
        toast(getString(R.string.pay_success))
        payTypePopupWindow.dismiss()
        OrderListActivity.open(this, 2)
        finish()
    }

    private fun showPayPopup(it: OrderSubmitEntity) {
        payTypePopupWindow.run {
            setData(it)
            showPopupWindow()
        }
    }
}